<template>
  <div id="viewDiv">
    <legendLayer />
    <div class="computeArea" @click="area">计算</div>
  </div>
</template>

<script>
import { EsriNameSpace } from '../api/arcgis/esri-namespace'
import { mapCenter, mapZoom } from '../../public/arcgisParam/arcgisParam'
import { AddGraphics } from '../lib/addGraphic'
import { CreateSymbol } from '../lib/createSymbol'
import ArcgisUtils from '../lib/arcgisUtils'
import legendLayer from '../views/Legend-layer'

export default {
  name: 'ArcgisMap',
  components: {
    legendLayer,
  },
  data() {
    return {
      EsriNameSpace: new EsriNameSpace(),
      CreateSymbol: new CreateSymbol(),
      ArcgisUtils: new ArcgisUtils(),
      // addGraphic: null,
      // ZGMap: '',
      // ZGMapView: '',
      // SceneView: '',
      // pointData: [],
    }
  },
  mounted() {
    //接收数据
    this.$bus.$on('gggg-click', (layerId) => {
      this.ArcgisUtils.setLayerVisible(this.ZGMap, layerId)
    })

    this.pointData = [
      [112.336510272702, 35.9375347654577, '35kv变电站01'],
      [112.336519138382, 35.9380612998955, '35kv变电站02'],
      [112.336517749146, 35.9379787938171, '35kv变电站03'],
      [112.336508667625, 35.9374394381861, '35kv变电站04'],
      [112.336152023699, 35.9162468126689, '安2站01'],
      [112.336144294555, 35.9157872827251, '安2站02'],
      [112.336146193614, 35.9159001906724, '安2站03'],
      [112.336153766843, 35.9163504484143, '安2站04'],
      [112.336661034724, 35.9464866858773, '安1站01'],
      [112.336670020971, 35.9470201445465, '安1站02'],
      [112.336672318062, 35.9471565065923, '安1站03'],
      [112.336663316395, 35.9466221361285, '安1站04'],
    ]
    this.lineData = [
      [
        [145.638962801406, 4.60814213875861],
        [145.639185892171, 4.60847116640474],
        [145.639506528776, 4.60854220151433],
        [145.639915872924, 4.60875785618097],
        [145.639540011489, 4.60948474919162],
        [145.639306623332, 4.60969427344154],
        [145.639306796339, 4.60975909793294],
        [145.639413907827, 4.60982809591668],
        [145.639634567985, 4.61006350492532],
        [145.639707316458, 4.61032236166866],
        [145.640136623174, 4.61062460598009],
        [145.640357702071, 4.61096811755813],
        [145.640799015495, 4.61134621902392],
        [145.64114697595, 4.61152146143101],
        [145.641542514109, 4.61194510710528],
        [145.641701514476, 4.61228260797198],
        [145.642060924875, 4.61269119750553],
        [145.642140407961, 4.61291054628222],
        [145.642129461974, 4.61302137174818],
        [145.641793303895, 4.61351601185277],
        [145.641679293348, 4.61374742442394],
      ],
      [
        [120.789729, 32.052285],
        [118.389729, 32.532285],
        [119.902167, 32.046901],
      ],
    ]
    this.polygonData = [
      [
        [119.789729, 32.052285],
        [118.902167, 32.046901],
        [118.630599, 32.091996],
        [119.789729, 32.052285],
      ],
      [
        [119.389729, 32.532285],
        [118.502167, 32.146901],
        [118.630599, 32.091996],
        [119.789729, 32.052285],
        [119.389729, 32.532285],
      ],
    ]
    this.EsriNameSpace.initNameSpace().then(() => {
      // 初始化地图
      this.initMap(mapCenter, mapZoom).then((initMapData) => {
        this.clickEventLayer(initMapData.view)
        this.moveEventLayer(initMapData.view)
        this.addGraphic = new AddGraphics(initMapData.map, this.EsriNameSpace)
        console.log('加addGraphic类')
        // 加面
        this.addGraphic.addGraphics(
          'polygon',
          'polygon2020',
          this.polygonData,
          this.CreateSymbol.createSimpleFillSymbol(
            [0, 200, 179],
            'solid',
            '#33333',
            5
          )
        )
        //layerType, layerTitle/id, data, symbol
        // 加线
        this.addGraphic.addGraphics(
          'polyline',
          'testpolyline',
          this.lineData,
          this.CreateSymbol.createSimpleLineSymbol('lightblue', '8px', 'solid')
        )

        // 加点
        this.addGraphic.addGraphics(
          'point',
          'test',
          this.pointData,
          this.CreateSymbol.createPointPictureMarker(
            'https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png',
            24,
            24,
            0,
            0
          )
        )

        // 加注记
        this.addGraphic.addTextGraphics('point', 'Text', this.pointData)
        const hh = this.addGraphic.createGraphicsLayer('sketch')
        this.addGraphic.mapAddLayer(initMapData.map, hh)
        const sketch = new this.EsriNameSpace.Sketch({
          layer: hh,
          view: initMapData.view,
          creationMode: 'single',
          layout: 'vertical',
        })
        initMapData.view.ui.add(sketch, 'top-right')
      })
    })
  },
  methods: {
    initMap(center, zoom) {
      return new Promise(async (resolve, reject) => {
        console.log('初始化地图--ING')
        // this.ZGMap = new this.EsriNameSpace.Map({
        //   basemap: 'dark-gray',
        // })

        const layerNew = new this.EsriNameSpace.TileLayer({
          url:
            'http://61.177.187.244:6011/arcgis/rest/services/yzslnew/MapServer',
          spatialReference: new this.EsriNameSpace.SpatialReference({
            wkid: 4326,
          }),
          tileInfo: new this.EsriNameSpace.TileInfo({
            dpi: 96,
            rows: 256,
            cols: 256,
            format: 'JPEG',
            compressionQuality: 75,
            origin: {
              x: -180,
              y: 90,
            },
            spatialReference: new this.EsriNameSpace.SpatialReference({
              wkid: 4326,
            }),
            lods: [
              {
                level: 17,
                resolution: 5.364418029785158e-6,
                scale: 2254.4677204799655,
              },
              {
                level: 18,
                resolution: 2.682209014892579e-6,
                scale: 1127.2338602399827,
              },
              {
                level: 19,
                resolution: 1.3411045074462895e-6,
                scale: 563.6169301199914,
              },
            ],
          }),
        })

        const layers = new this.EsriNameSpace.TileLayer({
          url:
            'http://61.177.187.244:6011/arcgis/rest/services/yzyx2014/MapServer',
          spatialReference: new this.EsriNameSpace.SpatialReference({
            wkid: 4326,
          }),
        })

        const NJlayers = new this.EsriNameSpace.FeatureLayer({
          url:
            'http://172.16.0.184:6080/arcgis/rest/services/02NJPeopleSafe/NJPeopleSafe/MapServer/0',
          // spatialReference: new this.EsriNameSpace.SpatialReference({
          //   wkid: 4326,
          // }),
          id: 'nj',
        })

        this.ZGMap = new this.EsriNameSpace.Map({
          // basemap: {
          //    baseLayers: [NJlayers],
          // },
          basemap: 'satellite',
          // spatialReference: new this.EsriNameSpace.SpatialReference({
          //   wkid: 4326,
          // }),
        })
        console.log(this.ZGMap)

        this.ZGMapView = new this.EsriNameSpace.MapView({
          map: this.ZGMap, // 地图类型样式
          container: 'viewDiv', // 地图容器
          center: center,
          zoom: zoom,
          popup: {
            // autoOpenEnabled	:false,
            collapseEnabled: false,
            alignment: 'top-center',
          },
          constraints: {
            // minScale: 500000,
            maxScale: 0,
            rotationEnabled: false, // 禁止旋转
          },
          navigation: {
            gamepad: {
              enabled: false,
            },
            browserTouchPanEnabled: false,
            momentumEnabled: false,
            mouseWheelZoomEnabled: true,
          },
        })
        resolve({ map: this.ZGMap, view: this.ZGMapView })
      })
    }, // end
    query(event) {
      let layer = this.ZGMap.findLayerById('nj')
      let query = layer.createQuery()
      query.geometry = this.ZGMapView.toMap(event)
      // query.geometry = {
      //   type: 'point',
      //   longitude: event.mapPoint.x,
      //   latitude: event.mapPoint.y,
      // }
      query.distance = 10
      query.units = 'miles'
      query.returnGeometry = true
      query.outFields = '*'
      query.spatialRelationship = 'intersects'
      let a = layer.queryFeatures(query).then((res) => {
        const features = res.features
        if (features && features.length > 0) {
          const feature = features[0]
          console.log(feature)
        }
      })
    },
    // 鼠标的点击事件
    clickEventLayer(mapView) {
      mapView.on('click', (event) => {
        mapView.hitTest(event).then((response) => {
          this.query(event)
          // console.log(response)
          if (response.results.length > 0) {
            const currentGraphic = response.results.filter((result) => {
              return result.graphic.layer
            })[0].graphic
            // console.log(currentGraphic)

            var lat = Math.round(event.mapPoint.latitude * 1000000) / 1000000
            var lon = Math.round(event.mapPoint.longitude * 1000000) / 1000000
            var measureThisAction = {
              title: 'Measure Length',
              id: 'measure-this',
              image:
                'https://developers.arcgis.com/javascript/latest/sample-code/popup-actions/live/Measure_Distance16.png',
            }
            // mapView.popup.open({
            //   // Set the popup's title to the coordinates of the location
            //   // title: 'Reverse geocode: [' + lon + ', ' + lat + ']',
            //   location: event.mapPoint, // Set the location of the popup to the clicked location
            //   actions: [measureThisAction],
            //   container:
            //     "<div style='max-width: 156px;overflow: hidden;height: 100%;margin-top: 13px;word-wrap:break-word'>" +
            //     "<p style='font-size: 14px;color: #333333; margin: 0;'>" +
            //     '分所给他被告人发我' +
            //     '</p>' +
            //     '</div>',
            // })

            /**
             * 点击有Graphic数据的时候，如果是相应的面数据，改变相应的样式
             */
            if (currentGraphic.layer.title == 'polygon2020') {
              for (const graphic of currentGraphic.layer.graphics.items) {
                // 面的初始样式
                graphic.symbol = this.CreateSymbol.createSimpleFillSymbol(
                  [0, 200, 179],
                  'solid',
                  '#33333',
                  5
                )
              }
              // 面的选择样式
              currentGraphic.symbol = this.CreateSymbol.createSimpleFillSymbol(
                'blue',
                'solid',
                'darkblue',
                1
              )
            }
          }
        })
      })
    }, // end click

    // 鼠标移动事件
    moveEventLayer(mapView) {
      mapView.on('pointer-move', (event) => {
        mapView.hitTest(event).then((response) => {
          if (response.results.length > 0) {
            document.body.style.cursor = 'pointer'
          } else {
            document.body.style.cursor = 'default'
          }
        })
      })
    }, // end moveEvent
    area() {
      const sketchLayer = this.ZGMap.findLayerById('sketch')
      const polygon2020 = this.ZGMap.findLayerById('polygon2020')

      // console.log(sketchLayer)
      this.computeArea(polygon2020, sketchLayer)
    }, // area
    computeArea(polygonLayer, drawLayer) {
      // 遍历已知的面 和 画的面进行拓扑关系检查
      /**
       * 1、已知的面包含画的面，计算画的面的面积
       * 2、已知的面与画的面相交，计算相交的面的面积
       * 3、画的面与多个已知的相交，计算相交的面的面积
       */
      const geoEngine = this.EsriNameSpace.geometryEngine
      const webMercatorUtils = this.EsriNameSpace.webMercatorUtils
      const polygonItems = polygonLayer.graphics.items
      const drawItems = drawLayer.graphics.items
      console.log(polygonItems)

      for (const polygonItem of polygonItems) {
        for (const drawItem of drawItems) {
          const ll = webMercatorUtils.webMercatorToGeographic(drawItem.geometry)
          if (geoEngine.intersects(ll, polygonItem.geometry)) {
            const kk = geoEngine.intersect(ll, polygonItem.geometry)
            const hhh = geoEngine.geodesicArea(kk, 'square-kilometers')
            console.log(hhh)
          }
        }
      }
    },
  }, //end methods
}
</script>

<style lang="less">
#viewDiv {
  width: 100vw;
  height: 100vh;
}

#viewDiv
  > div.esri-view-root
  > div.esri-ui
  > div.esri-ui-inner-container.esri-ui-manual-container
  > div.esri-component.esri-popup.esri-popup--aligned-top-center.esri-popup--shadow {
  background-color: rgba(212, 25, 123, 0.7);
}

// .esri-popup__pointer-direction {
//   width: 0;
//   height: 0;
// }
// .esri-popup__main-container {
//   background-color: red;
// }
// .esri-feature {
//   background-color: blue;
// }
// .esri-popup__button:hover {
//   background: #000;
// }
.computeArea {
  position: absolute;
  bottom: 100px;
  left: 100px;
  background-color: blue;
}
</style>
